package com.pospi.pai.yunpos.report;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.pospi.callbacklistener.HttpCallBackListener;
import com.pospi.http.HttpConnection;
import com.pospi.pai.yunpos.R;
import com.pospi.pai.yunpos.base.Base2Activity;
import com.pospi.pai.yunpos.been.SupBeen;
import com.pospi.pai.yunpos.login.Constant;
import com.pospi.pai.yunpos.util.BillUtil;
import com.pospi.util.DoubleSave;
import com.pospi.util.GetData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;
import lecho.lib.hellocharts.view.PieChartView;
import lib.kingja.switchbutton.SwitchMultiButton;

public class XsPiReportActivity extends Base2Activity {
    @Bind(R.id.switch_button)
    SwitchMultiButton switch_button;

    @Bind(R.id.tv_lx)
    TextView tv_lx;
    @Bind(R.id.tv_md)
    TextView tv_md;
    @Bind(R.id.time_start_select)
    TextView time_start_select;
    @Bind(R.id.time_end_select)
    TextView time_end_select;
    @Bind(R.id.pie_xs_chart)
    PieChartView pie_xs_chart;
    @Bind(R.id.pie_ml_chart)
    PieChartView pie_ml_chart;
    @Bind(R.id.pie_sl_chart)
    PieChartView pie_sl_chart;
    @Bind(R.id.pie_cb_chart)
    PieChartView pie_cb_chart;
    @Bind(R.id.ll_lx)
    LinearLayout ll_lx;
    @Bind(R.id.ll_md)
    LinearLayout ll_md;
    @Bind(R.id.list_xs)
    ListView list_xs;
    @Bind(R.id.rb_fl)
    RadioButton rb_fl;
    @Bind(R.id.rb_pp)
    RadioButton rb_pp;
    @Bind(R.id.rg)
    RadioGroup rg;

    private String thje;
    private String zje;
    private String xsje;
    private List<SupBeen> lx_Beens = new ArrayList<>();//类型
    private List<SyyBeen> syy_Beens = new ArrayList<>();//收银员
    private List<SupBeen> md_Beens = new ArrayList<>();//门店
    private String syyname;
    String[] date = {"5-23","5-22","6-22","5-23","5-22","2-22","5-22","4-22","9-22","10-22","11-22","12-22","1-22","6-22","5-23","5-22","2-22","5-22","4-22","9-22","10-22","11-22","12-22","4-22","9-22","10-22","11-22","zxc"};//X轴的标注
    int[] score= {74,22,18,79,20,74,20,74,42,90,74,42,90,50,42,90,33,10,74,22,18,79,20,74,22,18,79,20};//图表的数据
    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<PointValue> mPointValues1 = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();
    private int[] colorData = {
            Color.parseColor("#B0E0E6"),
            Color.parseColor("#F0E68C"),
            Color.parseColor("#D2B48C"),
            Color.parseColor("#A0522D"),
            Color.parseColor("#BC8F8F"),
            Color.parseColor("#87CEFA"),
            Color.parseColor("#2F4F4F"),
            Color.parseColor("#4B0082"),
            Color.parseColor("#FF00FF"),
            Color.parseColor("#00008B"),
            Color.parseColor("#5F9EA0"),
            Color.parseColor("#708090"),
            Color.parseColor("#00FF7F"),
            Color.parseColor("#E6E6FA")};
    //数据
    private PieChartData pieChardata;
    private PieChartData pieChardataml;
    private PieChartData pieChardataSl;
    private PieChartData pieChardatamlJj;
    private List<SliceValue> values = new ArrayList<SliceValue>();
    private List<SliceValue> valuesMl = new ArrayList<SliceValue>();
    private List<SliceValue> valuesSl = new ArrayList<SliceValue>();
    private List<SliceValue> valuesJj = new ArrayList<SliceValue>();
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.fragment_xs_pi);
        ButterKnife.bind(this);
        setTitle(SPHelper.getInstance().getString(Constant.STORE_NAME)+"销售对比图");
        time_start_select.setText(GetData.getYYMMDDTime());
        time_end_select.setText(GetData.getYYMMDDTime());
        new BillUtil().initBilltype(lx_Beens);
        ll_lx.setVisibility(View.GONE);
        ll_md.setVisibility(View.GONE);
        adapter = new MyAdapter();
        list_xs.setAdapter(adapter);
        rb_fl.setChecked(true);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_fl:
                        type = "3";
                        searchBillfast();
                        break;
                    case R.id.rb_pp:
                        type = "4";
                        searchBillfast();
                        break;
                }
            }
        });
        init();
        down();
//        downmd();

    }


    @OnClick({R.id.tv_lx,R.id.tv_md,  R.id.bt_search, R.id.time_start_select, R.id.time_end_select})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_lx:
//                showlx(tv_lx);
                break;
            case R.id.tv_md:
//                showmd(tv_md);
                break;
            case R.id.bt_search:
                searchBillfast();
                switch_button.clearSelection();
                break;
            case R.id.time_start_select:
                showDate(time_start_select);
                break;
            case R.id.time_end_select:
                showDate(time_end_select);
                break;
        }
    }

    private void init() {

        switch_button.setText("今天", "昨天", "近三天", "近七天", "本月");
        switch_button.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                switch (position) {
                    case 0:
                        startrq = GetData.getAnyTime(0);
                        endrq = GetData.getAnyTime(0);
                        time_start_select.setText(startrq);
                        time_end_select.setText(endrq);
                        searchBillfast();
                        break;
                    case 1:
                        startrq = GetData.getAnyTime(1);
                        endrq = GetData.getAnyTime(1);
                        time_start_select.setText(startrq);
                        time_end_select.setText(endrq);
                        searchBillfast();
                        break;
                    case 2:
                        startrq = GetData.getAnyTime(3);
                        endrq = GetData.getAnyTime(0);
                        time_start_select.setText(startrq);
                        time_end_select.setText(endrq);
                        searchBillfast();
                        break;
                    case 3:
                        startrq = GetData.getAnyTime(7);
                        endrq = GetData.getAnyTime(0);
                        time_start_select.setText(startrq);
                        time_end_select.setText(endrq);
                        searchBillfast();
                        break;
                    case 4:
                        startrq = GetData.getFirstDate();
                        endrq = GetData.getAnyTime(0);
                        time_start_select.setText(startrq);
                        time_end_select.setText(endrq);
                        searchBillfast();
                        break;


                }
            }
        });
        searchBillfast();


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    closeLodindDialog();
                    if (topBeens.size() == 0) {
                        setbill(false);
                    } else {
                        values.clear();
                        valuesMl.clear();
                        valuesSl.clear();
                        valuesJj.clear();
                        setPieChartData();
                        initPieChart();
                        initPieMlChart();
                        initPieSlChart();
                        initPieJjChart();
                        adapter.notifyDataSetChanged();
                        setbill(true);
                    }

                    break;
                case 2:

                    break;
                case 3:

                    break;
                case 4:

                    break;
            }

        }
    };

    private void setbill(boolean o) {
        if (o) {
//            bill_num_title.setVisibility(View.VISIBLE);
//            tv_list_title.setText("总销售额：");
//            total_je.setText(je);
//            bill_num.setText("" + count);
//            tv_xs.setText(xsje);
//            tv_th.setText(thje);
//            tv_hjje.setText(zje);

        } else {
            Toast.makeText(this, "未查询到信息", Toast.LENGTH_SHORT).show();
//            total_je.setText("");
//            bill_num.setText("");
//            tv_xs.setText("0");
//            tv_th.setText("0");
//            tv_hjje.setText("0");
            topBeens.clear();
        }

    }



    private String startrq = GetData.getAnyTime(0);
    private String endrq = GetData.getAnyTime(0);
    private String type = "3";
    private void searchBillfast() {
        showLodingDialog("请求中...");
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "report.mxsfx");
        params.put("fun", "find_xsfb");
        params.put("tjfs", type);
        JSONObject object = new JSONObject();
        try {
            object.put("startrq", time_start_select.getText().toString());
            object.put("endrq", time_end_select.getText().toString());
            object.put("market", SPHelper.getInstance().getString(Constant.STORE_ID));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("login", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    Log.i("login", jsonObject.getString("errMsg"));
                    JSONArray result = jsonObject.getJSONArray("result");
                    getResult(result);
                    Message message = Message.obtain();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }
        });

    }

    List<XsCatPiBeen> topBeens = new ArrayList<>();

    private void getResult(JSONArray result) {
        topBeens.clear();
        for (int i = 0; i < result.length(); i++) {
            try {
                JSONObject object = result.getJSONObject(i);
                XsCatPiBeen been = new Gson().fromJson(object.toString(), XsCatPiBeen.class);
                topBeens.add(been);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    //下载收银员
    private void down() {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getsyy");
        params.put("market", SPHelper.getInstance().getString(Constant.STORE_ID));
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    syy_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SyyBeen>>() {
                    }.getType());
                    syy_Beens.add(new BillUtil().getNewSyy());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    //下载
    private void downmd() {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastmarket");
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    md_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SupBeen>>() {
                    }.getType());

                    md_Beens.add(new BillUtil().getNewSup());
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        });


    }




    private void showlx(View v) {
        List<String> strings = new ArrayList<>();
        strings.clear();
        for (SupBeen been : lx_Beens) {
            strings.add(been.getName());
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_yyy, null);
        final PopupWindow yyyPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        yyyPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        yyyPopupWindow.setFocusable(true);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int height = contentView.getMeasuredHeight();
        int width = contentView.getMeasuredWidth();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
//        yyyPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - width / 2, location[1]);
        yyyPopupWindow.showAsDropDown(v);

        ListView listView = contentView.findViewById(R.id.yyy_list);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv_lx.setText(lx_Beens.get(position).getName());
                type = lx_Beens.get(position).getId();
                yyyPopupWindow.dismiss();
            }
        });
    }

    private void showDate(final TextView tv) {
        final Calendar c = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(XsPiReportActivity.this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                c.set(year, monthOfYear, dayOfMonth);
                tv.setText(DateFormat.format("yyyy-MM-dd", c));

            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    /**
     * 初始化
     */
    private void initPieChart() {
        pieChardata = new PieChartData();
        pieChardata.setHasLabels(true);//显示表情
        pieChardata.setHasLabelsOnlyForSelected(false);//不用点击显示占的百分比
        pieChardata.setHasLabelsOutside(false);//占的百分比是否显示在饼图外面
        pieChardata.setHasCenterCircle(true);//是否是环形显示
        pieChardata.setValues(values);//填充数据
        pieChardata.setCenterCircleColor(Color.WHITE);//设置环形中间的颜色
        pieChardata.setCenterCircleScale(0);//设置环形的大小级别
        pie_xs_chart.setPieChartData(pieChardata);
        pie_xs_chart.setValueSelectionEnabled(true);//选择饼图某一块变大
        pie_xs_chart.setAlpha(0.9f);//设置透明度
        pie_xs_chart.setCircleFillRatio(1f);//设置饼图大小

    }
    private void initPieMlChart() {
        pieChardata = new PieChartData();
        pieChardata.setHasLabels(true);//显示表情
        pieChardata.setHasLabelsOnlyForSelected(false);//不用点击显示占的百分比
        pieChardata.setHasLabelsOutside(false);//占的百分比是否显示在饼图外面
        pieChardata.setHasCenterCircle(true);//是否是环形显示
        pieChardata.setValues(valuesMl);//填充数据
        pieChardata.setCenterCircleColor(Color.WHITE);//设置环形中间的颜色
        pieChardata.setCenterCircleScale(0);//设置环形的大小级别
        pie_ml_chart.setPieChartData(pieChardata);
        pie_ml_chart.setValueSelectionEnabled(true);//选择饼图某一块变大
        pie_ml_chart.setAlpha(0.9f);//设置透明度
        pie_ml_chart.setCircleFillRatio(1f);//设置饼图大小

    }
    private void initPieJjChart() {
        pieChardata = new PieChartData();
        pieChardata.setHasLabels(true);//显示表情
        pieChardata.setHasLabelsOnlyForSelected(false);//不用点击显示占的百分比
        pieChardata.setHasLabelsOutside(false);//占的百分比是否显示在饼图外面
        pieChardata.setHasCenterCircle(true);//是否是环形显示
        pieChardata.setValues(valuesJj);//填充数据
        pieChardata.setCenterCircleColor(Color.WHITE);//设置环形中间的颜色
        pieChardata.setCenterCircleScale(0);//设置环形的大小级别
        pie_cb_chart.setPieChartData(pieChardata);
        pie_cb_chart.setValueSelectionEnabled(true);//选择饼图某一块变大
        pie_cb_chart.setAlpha(0.9f);//设置透明度
        pie_cb_chart.setCircleFillRatio(1f);//设置饼图大小

    }
    private void initPieSlChart() {
        pieChardata = new PieChartData();
        pieChardata.setHasLabels(true);//显示表情
        pieChardata.setHasLabelsOnlyForSelected(false);//不用点击显示占的百分比
        pieChardata.setHasLabelsOutside(false);//占的百分比是否显示在饼图外面
        pieChardata.setHasCenterCircle(true);//是否是环形显示
        pieChardata.setValues(valuesSl);//填充数据
        pieChardata.setCenterCircleColor(Color.WHITE);//设置环形中间的颜色
        pieChardata.setCenterCircleScale(0);//设置环形的大小级别
        pie_sl_chart.setPieChartData(pieChardata);
        pie_sl_chart.setValueSelectionEnabled(true);//选择饼图某一块变大
        pie_sl_chart.setAlpha(0.9f);//设置透明度
        pie_sl_chart.setCircleFillRatio(1f);//设置饼图大小

    }
    /**
     * 获取数据
     */
    private void setPieChartData() {
        initData();
        for (int i = 0; i < topBeens.size(); ++i) {
            SliceValue sliceValue = new SliceValue( topBeens.get(i).getXsbl(),colorData[i]);
            sliceValue.setLabel(Math.round(topBeens.get(i).getXsbl()) + "%");
            values.add(sliceValue);
            SliceValue sliceValueml = new SliceValue( topBeens.get(i).getMlebl(),colorData[i]);
            sliceValueml.setLabel(Math.round(topBeens.get(i).getMlebl()) + "%");
            valuesMl.add(sliceValueml);
            SliceValue sliceValuemSl = new SliceValue( topBeens.get(i).getPxs(),colorData[i]);
            sliceValuemSl.setLabel(Math.round(topBeens.get(i).getSlbl()) + "%");
            valuesSl.add(sliceValuemSl);
            SliceValue sliceValuemJj = new SliceValue( topBeens.get(i).getJjje(),colorData[i]);
            sliceValuemJj.setLabel(Math.round(topBeens.get(i).getJjbl()) + "%");
            valuesJj.add(sliceValuemJj);
        }
    }
    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return topBeens.size();
        }

        @Override
        public Object getItem(int position) {
            return topBeens.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                holder = new Holder();
                convertView = LayoutInflater.from(XsPiReportActivity.this).inflate(R.layout.item_pie_chart, null);
                holder.name = convertView.findViewById(R.id.tv_name);
                holder.bg = convertView.findViewById(R.id.tv_bg);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            holder.name.setText(type.equals("3") ? topBeens.get(position).getCatname() : topBeens.get(position).getBrandname());
            holder.bg.setBackgroundColor(colorData[position]);
            return convertView;
        }

        class Holder {
            TextView name;
            TextView bg;
        }
    }
    private void initData(){
        float xsSum = 0;
        float mleSum = 0;
        float slSum = 0;
        float jjSum = 0;
        for (XsCatPiBeen been : topBeens) {
            xsSum += been.getXsje();
            mleSum += been.getMle();
            slSum += been.getPxs();
            jjSum += been.getJjje();
        }
        for (XsCatPiBeen been : topBeens) {
            been.setXsbl(been.getXsje() / xsSum * 100);
            been.setMlebl(been.getMle() / mleSum * 100);
            been.setSlbl(been.getPxs() / slSum * 100);
            been.setJjbl(been.getJjje() / jjSum * 100);
        }

    }

}
